import { FC, useEffect } from 'react';
import { Form, Input, Button, Checkbox } from 'antd';

import { loginApi } from '@/utils/api';
import { history } from 'umi';

/*
  登录接口
    url: http://pudge.wang:3000/api/users/login
    method: POST
    data: 
      password: string
      username: string

  admin 123456
  zhangsan 123
*/

const Login: FC = () => {
  const [form] = Form.useForm();

  useEffect(() => {
    const remember = localStorage.getItem('remember');
    if (remember) {
      form.setFieldsValue({
        remember: true,
        username: localStorage.getItem('username'),
        password: localStorage.getItem('password'),
      });
    }
  }, []);
  const onFinish = async (values: any) => {
    if (values.remember) {
      localStorage.setItem('remember', '1');
      localStorage.setItem('username', values.username);
      localStorage.setItem('password', values.password);
    } else {
      localStorage.clear();
    }
    const res = await loginApi({
      username: values.username,
      password: values.password,
    });
    if (res.status === 0) {
      localStorage.setItem('token', res.result[0]._id);
      localStorage.setItem('auth', JSON.stringify(res.result[0].auth));
      localStorage.setItem('username', res.result[0].username);
      history.push('/admin/welcome');
    }
  };

  return (
    <div style={{ width: 400, height: 300, margin: '50px auto' }}>
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        // initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="Username"
          name="username"
          rules={[{ required: true, message: 'Please input your username!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Password"
          name="password"
          rules={[{ required: true, message: 'Please input your password!' }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          name="remember"
          valuePropName="checked"
          wrapperCol={{ offset: 8, span: 16 }}
        >
          <Checkbox>Remember me</Checkbox>
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Login;
